import { useState, useContext } from "react"
import { AppContext } from "../AppProvider"
let TodoInput = () => {
    //使用状态
    let { state: { data }, dispatch } = useContext(AppContext)
    //输入框的输入值
    let [val, setVal] = useState<string>('')
    //输入框的输入值变化的时候
    let handleInputChange = (e: any) => {
        setVal(e.target.value)
    }
    //添加todo
    let addTodo = () => {
        //非空校验
        if(!val.trim()) return
        let obj = {
            id: Math.random().toString(16).slice(2),
            todo: val,
            completed: false
        }
        dispatch({ type: 'ADD_TODO', payload: obj })
        setVal('')
    }
    return (
        <div className="input">
            <input type="text" placeholder="add todo" value={val} onChange={handleInputChange} />
            <button onClick={addTodo}>添加</button>
        </div>
    )
}

export default TodoInput